package com.itheima.reggie.controller;

import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")

public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;

    //添加菜品【复杂】
    @PostMapping
    public R addDish(@RequestBody DishDto dishDto) {
        //添加菜品
        dishService.insert(dishDto);
        return R.success("保存成功");
    }

    //分页查询菜品数据

    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        //设置分页
        Page<Dish> objectPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //    设置条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        //    排序
        lqw.orderByAsc(Dish::getUpdateTime);
        //     查询
        dishService.page(objectPage, lqw);
        //总条数
        long total = objectPage.getTotal();

        //R r = new R();
        //r.getMap().put("total", total);
        //HashMap map = new HashMap();
        //map.put("total", total);
        //objectPage.setTotal(total);

        //查询列表数据，回写分类
        List<Dish> records = objectPage.getRecords();

        //根据id设置分类
        List<DishDto> dishDtos = new ArrayList<>();

        for (Dish record : records) {
            //获取菜品id
            Long categoryId = record.getCategoryId();
            //获取菜品对象
            Category byId = categoryService.getById(categoryId);
            //获取菜品名称
            String name1 = byId.getName();
            //设置菜品
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(name1);
            //    将dish数据放入dishdto
            BeanUtils.copyProperties(record, dishDto);
            dishDtos.add(dishDto);
        }
        //map.put("records", dishDtos);
        //r.getMap().put("records", dishDtos);
        dishDtoPage.setRecords(dishDtos);
        dishDtoPage.setTotal(total);
        return R.success(dishDtoPage);
    }


   /* @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }*/

    //    根据id查询菜品数据，用于回显
    @GetMapping("/{id}")
    public R update(@PathVariable Long id) {

//查询菜品
        Dish dish1 = dishService.getById(id);
        Long id1 = dish1.getId();
//    查询口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dish1.getId());

        List<DishFlavor> list = dishFlavorService.list(lqw);


        DishDto dishDto = new DishDto();

        //设置
        BeanUtils.copyProperties(dish1, dishDto);

        dishDto.setFlavors(list);

        return R.success(dishDto);
    }

    //    修改菜品
    @PutMapping
    @Transactional
    public R putDish(@RequestBody DishDto dishDto) {
        //取出口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //修改菜品
        dishService.updateById(dishDto);
        //删除口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lqw);
        //    修改口味
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
            dishFlavorService.save(flavor);
        }

        return R.success("修改成功");
    }

    //    删除菜品
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        //System.out.println(ids);
        dishService.delete(ids);
        //dishService.removeByIds(ids);

        return R.success("删除成功");
    }

    //    起售停售
    @PostMapping("/status/{status}")
    public R status(@PathVariable int status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        //    设置status
        lqw.set(Dish::getStatus, status);
        lqw.in(Dish::getId, ids);

        dishService.update(lqw);

        return R.success("修改成功");

    }

    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    public R list(long categoryId) {
        //添加条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, categoryId);
        //查询集合
        List<Dish> list = dishService.list(lqw);

        //配合前端改造代码
        //ArrayList<DishDto> dishDtos = new ArrayList<>();
    /*    //将口味和菜品添加进disdtos

        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
        //    将菜品赋值到dishdto
            BeanUtils.copyProperties(dish,dishDto);
        //    将口味赋值给dishdto
            LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(lqw2);
            dishDto.setFlavors(flavors);
            dishDtos.add(dishDto);
        }*/
         List<DishDto> dishDtoList  = list.stream().map((dish)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            Long categoryId1 = dish.getCategoryId();
            Category byId = categoryService.getById(categoryId1);
            if(byId != null) {
                String name = byId.getName();
                dishDto.setCategoryName(name);
            }
            Long id = dish.getId();
            LambdaQueryWrapper<DishFlavor> lqwe = new LambdaQueryWrapper<>();
            lqwe.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lqwe);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

}
